/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package org.eclipse.iota.model;

import java.util.Collection;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.iota.IotaPackage;
import org.eclipse.iota.arithmetics.IotaOperationExecutor;
import org.eclipse.iota.util.IotaCopyUtil;

/**
 * @see org.eclipse.iota.IotaPackage#getLinearCombination()
 * @model kind="class"
 * @generated
 */
public class LinearCombination extends EObjectImpl implements HighLevelExpression {
	
	/**
	 * Derive a linear combination from a basic expression. 
	 * It returns <code>null</code> if no linear combination could be
	 * derived. The original expression is not modified
	 * 
	 * @param expression Expression.
	 * @return Linear combination.
	 * @generated NOT
	 */
	public static LinearCombination fromBasic(Expression expression) {
		
		LinearCombination linear = new LinearCombination();
		
		// Additions.
		if (expression instanceof Addition) {
			Addition addition = (Addition) expression;
			linear.setOffset(new Constant(0));
			
			for (Expression operand : addition.getOperands()) {
				if (operand instanceof Constant) {
					linear.getOffset().add((Constant) operand);
				}
				else if (operand instanceof Multiplication) {
					linear.add(toEntry((Multiplication) operand));
				} else {
					return null;
				}
			}			
		}
		
		// Multiplication
		else if (expression instanceof Multiplication) {
			linear.add(toEntry((Multiplication) expression));
		}
		
		// Check if it is a valid, non-empty linear combination.
		if (linear.getVariables().isEmpty() && (linear.getOffset()==null)) {
			return null;
		}
		
		return linear;
		
	}
	
	/*
	 * Helper method.
	 */
	private static LinearCombination toEntry(Multiplication multiplication) {
		
		// Initialize result.
		Constant factor = new Constant(1);
		Variable variable = null;
		
		// Iterate over all operands.
		for (Expression operand : multiplication.getOperands()) {
			if (operand instanceof Constant) {
				factor.multiply((Constant) operand);
			} else if (operand instanceof Variable) {
				if (variable!=null) return null;
				else variable = (Variable) operand;
			} else {
				return null;
			}
		}
		
		// Create the new linear entry:
		LinearCombination result = new LinearCombination();
		result.getVariables().add(variable);
		result.getFactors().add(factor);
		return result;
		
	}
	
	
	/**
	 * Add a linear combination to this linear combination.
	 * @param linear Argument linear combination.
	 * @generated NOT
	 */
	public void add(LinearCombination linear) {
		
		// Add factors.
		for (Variable variable : linear.getVariables()) {
			Constant factor = linear.getFactor(variable);
			if (getVariables().contains(variable)) {
				getFactor(variable).add(factor);
			} else {
				getVariables().add(variable);
				getFactors().add(factor.copy());
			}
		}
		
		// Add offsets.
		if (linear.getOffset()!=null) {
			if (getOffset()==null) setOffset(new Constant(0));
			getOffset().add(linear.getOffset());
		}
	}
	
	/**
	 * Subtract a linear combination from this linear combination.
	 * @param linear Argument linear combination.
	 * @generated NOT
	 */
	public void subtract(LinearCombination linear) {
		linear = IotaCopyUtil.copy(linear);
		add(linear.negate());
	}
	
	/**
	 * Negate this linear combination.
	 * @generated NOT
	 */
	public LinearCombination negate() {
		for (Constant factor : getFactors()) {
			factor.negate();
		}
		if (getOffset()!=null) {
			getOffset().negate();
		}
		return this;
	}
	
	/**
	 * Divide all factors and the offset in this 
	 * linear combination by the argument value.
	 * @param value Divisor.
	 */
	public void divide(Constant value) {
		for (Constant factor : getFactors()) {
			factor.divide(value);
		}
		if (getOffset()!=null) {
			getOffset().divide(value);
		}
	}

	/**
	 * Get the factor for a given variable.
	 * @param Variable variable.
	 * @return The factor (can be <code>null</code>).
	 */
	public Constant getFactor(Variable variable) {
		if (getVariables().contains(variable)) {
			int index = getVariables().indexOf(variable);
			if (getFactors().size()<=index) return null;
			else return getFactors().get(index);
		} else {
			return null;
		}
	}

	
	/**
	 * Convert this linear expression back to a basic expression.
	 * @return Basic expression.
	 * @generated NOT
	 */
	public Expression toBasic() {
		Expression result = new Constant(0);
		for (Variable variable : getVariables()) {
			Expression current = new Reference(variable);
			if (getFactor(variable)!=null) {
				current = IotaOperationExecutor.multiply(current, getFactor(variable));
			}
			result = IotaOperationExecutor.add(result, current);
		}
		if (getOffset()!=null) {
			result = IotaOperationExecutor.add(result, getOffset());
		}
		return result;
	}
	
	/**
	 * Get the equation that owns this expression.
	 * @generated NOT
	 */
	public Equation basicGetEquation() {
		if (eContainer() instanceof Equation) return (Equation) eContainer();
		if (eContainer() instanceof Expression) return ((Expression) eContainer()).getEquation();
		return null;
	}
	

	/**
	 * @generated NOT
	 */
	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		for (int i=0; i<getVariables().size(); i++) {
			Constant factor = getFactor(getVariables().get(i));
			if (factor!=null && !factor.isZero()) {
				if (i>0 && factor.isPositive()) result.append("+");
				result.append(factor + "*" + getVariables().get(i));
			}
		}
		if (getOffset()!=null && !getOffset().isZero()) {
			if (getOffset().isPositive()) result.append("+");
			result.append(getOffset());
		}
		return result.toString();
	}

	
	/* ---------------------------------------------------------------- *
	 * GENERATED CODE.                                                  *
	 * Do not edit below this line. If you need to edit, move it above  *
	 * this line and change the '@generated'-tag to '@generated NOT'.   *
	 * ---------------------------------------------------------------- */	
	
	/**
	 * The cached value of the '{@link #getVariables() <em>Variables</em>}' reference list.
	 * @see #getVariables()
	 * @generated
	 * @ordered
	 */
	protected EList<Variable> variables;
	
	/**
	 * The cached value of the '{@link #getFactors() <em>Factors</em>}' containment reference list.
	 * @see #getFactors()
	 * @generated
	 * @ordered
	 */
	protected EList<Constant> factors;

	/**
	 * The cached value of the '{@link #getOffset() <em>Offset</em>}' containment reference.
	 * @see #getOffset()
	 * @generated
	 * @ordered
	 */
	protected Constant offset;

	/**
	 * @generated
	 */
	public LinearCombination() {
		super();
	}

	/**
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return IotaPackage.Literals.LINEAR_COMBINATION;
	}

	/**
	 * Returns the value of the '<em><b>Equation</b></em>' reference.
	 * @return the value of the '<em>Equation</em>' reference.
	 * @see org.eclipse.iota.IotaPackage#getExpression_Equation()
	 * @model transient="true" changeable="false" volatile="true" derived="true"
	 * @generated
	 */
	public Equation getEquation() {
		Equation equation = basicGetEquation();
		return equation != null && equation.eIsProxy() ? (Equation)eResolveProxy((InternalEObject)equation) : equation;
	}


	/**
	 * Returns the value of the '<em><b>Factors</b></em>' containment reference list.
	 * The list contents are of type {@link org.eclipse.iota.model.Constant}.
	 * @return the value of the '<em>Factors</em>' containment reference list.
	 * @see org.eclipse.iota.IotaPackage#getLinearCombination_Factors()
	 * @model containment="true"
	 * @generated
	 */
	public EList<Constant> getFactors() {
		if (factors == null) {
			factors = new EObjectContainmentEList<Constant>(Constant.class, this, IotaPackage.LINEAR_COMBINATION__FACTORS);
		}
		return factors;
	}

	/**
	 * Returns the value of the '<em><b>Offset</b></em>' containment reference.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @return the value of the '<em>Offset</em>' containment reference.
	 * @see #setOffset(Constant)
	 * @see org.eclipse.iota.IotaPackage#getLinearCombination_Offset()
	 * @model containment="true"
	 * @generated
	 */
	public Constant getOffset() {
		return offset;
	}

	/**
	 * Returns the value of the '<em><b>Variables</b></em>' reference list.
	 * The list contents are of type {@link org.eclipse.iota.model.Variable}.
	 * @return the value of the '<em>Variables</em>' reference list.
	 * @see org.eclipse.iota.IotaPackage#getLinearCombination_Variables()
	 * @model
	 * @generated
	 */
	public EList<Variable> getVariables() {
		if (variables == null) {
			variables = new EObjectResolvingEList<Variable>(Variable.class, this, IotaPackage.LINEAR_COMBINATION__VARIABLES);
		}
		return variables;
	}

	/**
	 * @generated
	 */
	public NotificationChain basicSetOffset(Constant newOffset, NotificationChain msgs) {
		Constant oldOffset = offset;
		offset = newOffset;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, IotaPackage.LINEAR_COMBINATION__OFFSET, oldOffset, newOffset);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 * Sets the value of the '{@link org.eclipse.iota.model.LinearCombination#getOffset <em>Offset</em>}' containment reference.
	 * @param value the new value of the '<em>Offset</em>' containment reference.
	 * @see #getOffset()
	 * @generated
	 */
	public void setOffset(Constant newOffset) {
		if (newOffset != offset) {
			NotificationChain msgs = null;
			if (offset != null)
				msgs = ((InternalEObject)offset).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - IotaPackage.LINEAR_COMBINATION__OFFSET, null, msgs);
			if (newOffset != null)
				msgs = ((InternalEObject)newOffset).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - IotaPackage.LINEAR_COMBINATION__OFFSET, null, msgs);
			msgs = basicSetOffset(newOffset, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, IotaPackage.LINEAR_COMBINATION__OFFSET, newOffset, newOffset));
	}

	/**
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case IotaPackage.LINEAR_COMBINATION__FACTORS:
				return ((InternalEList<?>)getFactors()).basicRemove(otherEnd, msgs);
			case IotaPackage.LINEAR_COMBINATION__OFFSET:
				return basicSetOffset(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case IotaPackage.LINEAR_COMBINATION__EQUATION:
				if (resolve) return getEquation();
				return basicGetEquation();
			case IotaPackage.LINEAR_COMBINATION__VARIABLES:
				return getVariables();
			case IotaPackage.LINEAR_COMBINATION__FACTORS:
				return getFactors();
			case IotaPackage.LINEAR_COMBINATION__OFFSET:
				return getOffset();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case IotaPackage.LINEAR_COMBINATION__VARIABLES:
				getVariables().clear();
				getVariables().addAll((Collection<? extends Variable>)newValue);
				return;
			case IotaPackage.LINEAR_COMBINATION__FACTORS:
				getFactors().clear();
				getFactors().addAll((Collection<? extends Constant>)newValue);
				return;
			case IotaPackage.LINEAR_COMBINATION__OFFSET:
				setOffset((Constant)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case IotaPackage.LINEAR_COMBINATION__VARIABLES:
				getVariables().clear();
				return;
			case IotaPackage.LINEAR_COMBINATION__FACTORS:
				getFactors().clear();
				return;
			case IotaPackage.LINEAR_COMBINATION__OFFSET:
				setOffset((Constant)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case IotaPackage.LINEAR_COMBINATION__EQUATION:
				return basicGetEquation() != null;
			case IotaPackage.LINEAR_COMBINATION__VARIABLES:
				return variables != null && !variables.isEmpty();
			case IotaPackage.LINEAR_COMBINATION__FACTORS:
				return factors != null && !factors.isEmpty();
			case IotaPackage.LINEAR_COMBINATION__OFFSET:
				return offset != null;
		}
		return super.eIsSet(featureID);
	}

}
